package com.hans.scala.clazz

import scala.reflect.ClassTag
import java.sql.{DriverManager, ResultSet}
import scala.collection.mutable

/**
 * User: ZhangJuntao
 * Date: 2014/3/31
 * Time: 10:17
 */
class OtherClass[T: ClassTag](mapRow: (ResultSet) => T = DefaultParameterExample.resultSetToObjectArray _) {
  val conn = {
    classOf[com.mysql.jdbc.Driver]
    DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "root")
  }
  val stmt = conn.prepareStatement("select * from t_user", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
  val rs = stmt.executeQuery()

  def test() {
    val list = new mutable.ListBuffer[T]
    while (rs.next()) {
      list += mapRow(rs)
    }
    println(list)
  }
}

object DefaultParameterExample {
  def main(args: Array[String]) {

    val oc2 = new OtherClass(
      (rs: ResultSet) => {
        val rsMap: mutable.Map[String, Any] = mutable.Map.empty[String, Any]
        rsMap += ("id" -> rs.getString("id")) // id
        rsMap.toMap
      }
    )
    println(oc2.getClass) //class com.hans.scala.clazz.OtherClass
    oc2.test()

    val oc3 = new OtherClass {//注意{ }
      // == val oc3 = new OtherClass
      (rs: ResultSet) => {
        val rsMap: mutable.Map[String, Any] = mutable.Map.empty[String, Any]
        rsMap += ("id" -> rs.getString("id")) // id
        rsMap.toMap
      }
    }
    println(oc3.getClass) //class com.hans.scala.clazz.DefaultParameterExample$$anon$1
    oc3.test()

  }

  //缺省方法
  def resultSetToObjectArray(rs: ResultSet) = {
    Array.tabulate[Object](rs.getMetaData.getColumnCount)(i => rs.getObject(i + 1))
  }
}

